﻿using CommonHelper;
using CommonProject_DeskTop.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Security.Authentication.ExtendedProtection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace CommonProject_DeskTop
{

    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

        [System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "CreateMutex")]
        public static extern IntPtr CreateMutex(int lpSecurityAttributes, bool bInitialOwner, string lpName);

        [System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "GetLastError")]
        public static extern int GetLastError();
        private const int ERROR_ALREADY_EXISTS = 183;

        public static WelcomWindow welcom;
        protected override void OnStartup(StartupEventArgs e)
        {
            string appTitle = "CommonProject_DeskTop";
            IntPtr hMutex = CreateMutex(0, true, appTitle);
            if (GetLastError() == ERROR_ALREADY_EXISTS)
            {
                MessageBox.Show("已有一个客户端正在运行,请先结束原来客户端!");
                Environment.Exit(0);
                Application.Current.Shutdown();
                return;
            }
            base.OnStartup(e);

            Thread thread = new Thread(() =>
            {
                welcom = new WelcomWindow();
                welcom.ShowDialog();
            });
            thread.Name = "Welcome";
            thread.SetApartmentState(ApartmentState.STA);//设置为单线程
            thread.Start();

            //初始化
            if (DataCenter.Instance.Init())
            {
              
                Thread.Sleep(5000);
            }
            else
            {
                Application.Current.Shutdown();
                MessageBox.Show("系统配置数据异常,详细信息请查看错误日志", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            LogHelper.logSysRun.Warn("TaskException" + e.ToString());
            e.SetObserved();
        }
        private void App_DispatcherUnhandleException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            LogHelper.logSysRun.Warn("DispatcherException" + e.ToString());
            e.Handled = true;
        }
    }
}
